// src/utils/websocket.js

let ws = null;
let reconnectTimer = null;
let listeners = [];
// 连接状态
export const ConnectionState = {
  CONNECTING: 0,
  OPEN: 1,
  CLOSING: 2,
  CLOSED: 3
};

// 初始化WebSocket连接
export const initWebSocket = () => {
  if (ws && ws.readyState !== ConnectionState.CLOSED) {
    return;
  }

  // 替换为你的WebSocket服务器地址
  ws = new WebSocket('ws://localhost:8088');

  ws.onopen = () => {
    console.log('WebSocket连接已建立');
    clearReconnectTimer();
    // 通知所有监听器连接已建立
    notifyListeners({ type: 'connection', data: { state: ConnectionState.OPEN } });
  };

  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log('收到WebSocket消息:', data);

      // 通知所有监听器收到新消息
      notifyListeners(data);
    } catch (error) {
      console.error('解析WebSocket消息失败:', error);
    }
  };

  ws.onclose = (event) => {
    console.log('WebSocket连接已关闭', event.code);
    ws = null;

    // 通知所有监听器连接已关闭
    notifyListeners({ type: 'connection', data: { state: ConnectionState.CLOSED } });

    // 启动重连机制
    startReconnectTimer();
  };

  ws.onerror = (error) => {
    console.error('WebSocket发生错误:', error);
    ElMessage({
      type: 'error',
      message: 'WebSocket连接错误'
    });
  };
};

// 发送消息
export const sendMessage = (message) => {
  if (ws && ws.readyState === ConnectionState.OPEN) {
    console.log(message);
    ws.send(JSON.stringify(message));
    return true;
  }
  console.error('WebSocket未连接，无法发送消息');
  return false;
};

// 关闭WebSocket连接
export const closeWebSocket = () => {
  clearReconnectTimer();
  if (ws) {
    ws.close();
    ws = null;
  }
};

// 添加消息监听器
export const addMessageListener = (callback) => {
  if (typeof callback === 'function') {
    listeners.push(callback);
  }
};

// 移除消息监听器
export const removeMessageListener = (callback) => {
  listeners = listeners.filter(listener => listener !== callback);
};

// 通知所有监听器
const notifyListeners = (message) => {
  listeners.forEach(listener => listener(message));
};

// 启动重连计时器
const startReconnectTimer = () => {
  clearReconnectTimer();
  reconnectTimer = setTimeout(() => {
    console.log('尝试重新连接WebSocket...');
    initWebSocket();
  }, 3000); // 3秒后重试
};

// 清除重连计时器
const clearReconnectTimer = () => {
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
    reconnectTimer = null;
  }
};